package com.bootlever.framework.core.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.bootlever.framework.common.utils.StringUtils;
import com.bootlever.framework.core.properties.MonitorProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
//@ConditionalOnClass(DruidDataSource.class)
@ConditionalOnBean(DruidDataSource.class)
@DependsOn({"bootLeverMonitors"})
public class DruidConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);

    @Autowired
    private MonitorProperties monitorProperties;

    @Bean
    public ServletRegistrationBean statViewServlet() {
        logger.info("初始化Druid控制台");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //设置白名单
        servletRegistrationBean.addInitParameter("allow",monitorProperties.getDruidMonitor().getAllow());
        //设置黑名单
        if (StringUtils.isNotEmpty(monitorProperties.getDruidMonitor().getDeny())){
            servletRegistrationBean.addInitParameter("deny",monitorProperties.getDruidMonitor().getDeny());
        }
        //设置控制台管理用户登录名和密码
        servletRegistrationBean.addInitParameter("loginUsername",monitorProperties.getDruidMonitor().getUsername());
        String password = "";
        if (StringUtils.isNotEmpty(monitorProperties.getDruidMonitor().getPassword())) {
            password = monitorProperties.getDruidMonitor().getPassword();
        } else {
            password = StringUtils.getRandonStr(64);
        }
        logger.info("druid密码：{}", password);
        servletRegistrationBean.addInitParameter("loginPassword",password);
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable", monitorProperties.getDruidMonitor().getResetEnable().toString());
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean statFilter() {
        logger.info("初始化druid控制台过滤器");
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*png,*.css,*.ico,/druid/*,*.svg,*.jpeg");
        return  filterRegistrationBean;
    }
}
